package edu.fight.service;

import edu.fight.dao.UserDao;
import edu.fight.dto.JwtUser;
import edu.fight.entity.User;
import edu.fight.utils.RedisUtil;
import edu.fight.utils.RequestContextUtil;
import edu.fight.utils.jwt.JwtUtils;
import edu.fight.utils.jwt.RsaFileInMemory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.security.PrivateKey;

@Service
@Slf4j
public class UserService {

    @Autowired
    UserDao userDao;

    @Autowired
    RequestContextUtil requestContextUtil;

    @Autowired
    RedisUtil redisUtil;

    public User findByUsername(String username) {
        return userDao.findByUsername(username);
    }

    public String login(User userparam) throws Exception {
        String token = null;
        User userdb = userDao.findByUsername(userparam.getName());
        if(ObjectUtils.isEmpty(userdb)){
            throw new RuntimeException("用户不存在");
        }
        String passwd = userparam.getPasswd();
        if(!userdb.getPasswd().equals(passwd)){
            throw new RuntimeException("密码错误");
        }
        PrivateKey privateKey = RsaFileInMemory.getPrivateKey();
        JwtUser jwtUser = new JwtUser(userdb.getId(), userdb.getName());

        token = JwtUtils.generateToken(jwtUser, privateKey);
        return token;
    }

    /**
     * 模拟从http请求中获取jwt user
     */
    public void dobiz(){
        JwtUser jwtUser = requestContextUtil.getJwtUserFromRequest();
        log.info(jwtUser.getUsername()+"  "+jwtUser.getId());
    }

}
